import 'dart:async';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:gluz/app/data/user_profile_entity.dart';
import 'package:gluz/app_session.dart';

/// 原生桥接工具类
/// 用于Flutter和原生iOS/Android之间的方法调用
class NativeBridge {
  static const MethodChannel _methodChannel = MethodChannel('native_bridge');
  static const EventChannel _eventChannel = EventChannel('native_events');
  
  static final NativeBridge _instance = NativeBridge._internal();
  factory NativeBridge() => _instance;
  NativeBridge._internal();

  /// 初始化原生桥接
  /// 设置方法调用处理器和事件监听器
  static Future<void> initialize() async {
    try {
      // 设置方法调用处理器，用于原生调用Flutter方法
      _methodChannel.setMethodCallHandler(_handleMethodCall);
      
      // 设置事件监听器，用于接收原生发送的事件
      _eventChannel.receiveBroadcastStream().listen(_handleNativeEvent);
      
      print('NativeBridge initialized successfully');
    } catch (e) {
      print('Failed to initialize NativeBridge: $e');
    }
  }

  /// flutter调用原生
  static Future<dynamic> invokeMethodToNative(String methodName, Map<String, dynamic> data) async {
    try {
      return await _methodChannel.invokeMethod(methodName, data);
    } on PlatformException catch (e) {
      print('Failed invoke method to native: ${e.message}');
      return null;
    }
  }

  /// 处理原生调用Flutter的方法
  static Future<dynamic> _handleMethodCall(MethodCall call) async {
    try {
      switch (call.method) {
        case 'getUserInfo':
          return await _getUserInfo();
        default:
          throw PlatformException(
            code: 'METHOD_NOT_FOUND',
            message: 'Method ${call.method} not found',
          );
      }
    } catch (e) {
      print('Error handling method call ${call.method}: $e');
      return {'error': e.toString()};
    }
  }

  /// 获取用户信息 - 原生调用Flutter的方法
  static Future<Map<String, dynamic>> _getUserInfo() async {
    try {
      UserProfileEntity? user = app.getUser();
      if (user != null) {
        return {
          'success': true,
          'data': user.toJson(),
        };
      } else {
        return {
          'success': false,
          'message': '用户未登录'.tr,
        };
      }
    } catch (e) {
      return {
        'success': false,
        'message': '获取用户信息失败: $e'.tr,
      };
    }
  }

  /// 处理原生发送的事件
  static void _handleNativeEvent(dynamic event) {
    try {
      print('Received native event: $event');
      // 这里可以根据需要处理原生发送的事件
      // 比如通知UI更新、触发某些操作等
    } catch (e) {
      print('Error handling native event: $e');
    }
  }
} 